import React, { useEffect, useState } from 'react';
import { listMyChartByPageUsingPOST } from '@/services/zoffyBI/chartController';
import message from 'antd/es/message';
import { Card, List, Result, Space, Typography } from 'antd';
import ReactECharts from 'echarts-for-react';
import Search from 'antd/es/input/Search';
const { Paragraph } = Typography;
type SearchParams = {
  page?: number;
  pageSize?: number;
  name?: string;
  sortField?: string;
  sortOrder?: string;
};

const MyChart: React.FC = () => {
  const [chartList, setChartList] = useState<API.Chart[]>([]);
  const [searchParams, setSearchParams] = useState<SearchParams>({
    pageSize: 4,
    page: 1,
    name: '',
    sortField: 'create_time',
    sortOrder: 'desc',
  });
  const [total, setTotal] = useState<number>(0);
  const loadData = async () => {
    try {
      const res = await listMyChartByPageUsingPOST(searchParams);
      if (res?.data) {
        setChartList(res.data.records ?? []);
        setTotal(res.data.total ?? 0);
      } else {
        message.error('获取图表失败');
      }
    } catch (e: any) {
      message.error('获取图表失败');
    }
  };
  useEffect(() => {
    loadData();
  }, [searchParams]);

  return (
    <>
      <Search
        placeholder="在此输入查询内容"
        enterButton="查找"
        size="large"
        loading={false}
        onSearch={(value) => {
          setSearchParams({
            ...searchParams,
            page: 1,
            name: value,
          });
        }}
      />
      <Space />

      <List
        grid={{
          gutter: 16,
          xs: 1,
          sm: 1,
          md: 2,
          lg: 2,
          xl: 2,
          xxl: 2,
        }}
        itemLayout="horizontal"
        pagination={{
          onChange: (page, pageSize) => {
            setSearchParams({
              ...searchParams,
              page: page,
            });
          },
          pageSize: searchParams.pageSize,
          total: total,
        }}
        dataSource={chartList}
        renderItem={(item) => (
          <List.Item key={item.id}>
            <Card hoverable={true}>
              <List.Item.Meta title={item.name} description={item.goal} />
              {item.status == 'success' && (
                <>
                  <ReactECharts option={JSON.parse(item.genChart ?? '{}')} />
                  <Paragraph
                    ellipsis={{ rows: 3, expandable: true, symbol: 'more' }}
                    style={{ whiteSpace: 'pre-line' }}
                  >
                    {item.genResult}
                  </Paragraph>
                </>
              )}
              {item.status == 'wait' && <Result title="图表生成中" />}
              {item.status == 'fail' && <Result status="warning" title="生成失败" />}
            </Card>
          </List.Item>
        )}
      />
    </>
  );
};
export default MyChart;
